#include "../inc/stack.h"

/* initialize stack */
void init_stack(Stack *s) {
    s->top = -1;
    s->capacity = 2;
    s->size = 0;
    s->elements = (Data*)malloc(sizeof(Data) * s->capacity);
}

/* get the size of stack */
int get_stack_size(Stack *s){
    return s->size;
}

/* check whether the stack is empty */
int is_stack_empty(Stack *s) {
    return s->top == -1;
}

/* push a element into the stack */
void stack_push(Stack *s, void *data) {
    if (s->top == s->capacity - 1) {
        s->capacity *= 2;
        s->elements = (Data*)realloc(s->elements, sizeof(Data) * s->capacity);
    }
    s->top++;
    s->size++;
    s->elements[s->top].data = data;
}

/* pop a element from the stack  */
void* stack_pop(Stack *s) {
    if (is_stack_empty(s)) {
        return NULL;
    }
    void *data =s->elements[s->top].data;
    s->top--;
    s->size--;
    return data;
}

/* peek the top element of stack */
void *stack_peek(Stack *s) {
    if (is_stack_empty(s)) {
        return NULL;
    }
    return s->elements[s->top].data;
}

/* free the stack */
void free_stack(Stack *s){
    while(!is_stack_empty(s)){
        void *data = stack_pop(s);
        free(data);
    }
    free(s->elements);
    s->elements = NULL;
    s->top = -1;
    s->capacity = s->size = 0;
}
